//
//  CADisplayLink+UI.swift
//  Auscultation
//
//  Created by 来 on 2021/2/4.
//

import Foundation
import UIKit

extension CADisplayLink {
    class func lgf_RunTimer(_  target: AnyObject?, S: TimeInterval, handler: @escaping (CADisplayLink) -> Void) -> CADisplayLink {
        let displaylink = LGFDisplayLink.init().lgf_Run(S: S) { (link) in
            if target != nil {
                handler(link)
            } else {
                link.lgf_StopTimer()
            }
        }
        displaylink.add(to: .current, forMode: .default)
        return displaylink
    }
//    73300.46108254169
//    73300.47774854169
    func lgf_StopTimer() {
        self.invalidate()
    }
}

class LGFDisplayLink: CADisplayLink {
    var iii: TimeInterval = 0
    var interval: TimeInterval = 0
    var call: ((CADisplayLink) -> Void)?
    @discardableResult
    func lgf_Run(S: TimeInterval, handler: @escaping (CADisplayLink) -> Void) -> CADisplayLink {
        call = handler
        interval = S
        let displaylink = CADisplayLink(target: self, selector: #selector(run(_:)))
        displaylink.preferredFramesPerSecond = 0
        return displaylink
    }
    @objc private func run(_ sender: CADisplayLink) {
        debugPrint("计时器:")
        debugPrint(sender.duration)
        debugPrint(sender.timestamp)
        debugPrint(sender.targetTimestamp)
        debugPrint((sender.targetTimestamp - sender.timestamp) * 60)
        self.iii += (sender.targetTimestamp - sender.timestamp) * 60
        if self.iii >= self.interval * 60.0 {
            self.iii = 0
            self.call?(sender)
        }
    }
}
